extends HTTPRequest

@export var api_key := ""
var conversation := [
	{"role": "system", "content": "（你的 system prompt）"}
]

signal response_received(emotion: String, raw_text: String)

func _ready():
	_load_api_key()
	get_node("../UIManager").connect("send_request", self, "_on_send_request")

func _load_api_key():
	var cfg = ConfigFile.new()
	if cfg.load("res://config/secret.cfg") != OK:
		push_error("❌ 无法加载 API 密钥")
		return
	api_key = cfg.get_value("deepseek", "api_key", "")

func _on_send_request(user_text: String):
	conversation.append({"role": "user", "content": user_text})
	_call_api()

func _call_api():
	var req = HTTPRequest.new()
	add_child(req)
	req.request(
		"https://api.deepseek.com/chat/completions",
		["Content-Type: application/json", "Authorization: Bearer " + api_key],
		HTTPClient.METHOD_POST,
		JSON.stringify({
			"model": "deepseek-chat",
			"messages": conversation,
			"stream": false
		})
	)
	req.connect("request_completed", self, "_on_request_completed")

func _on_request_completed(result, code, headers, body):
	if result == HTTPRequest.RESULT_SUCCESS and code == 200:
		var js = JSON.parse(body.get_string_from_utf8())
		var msg = js.result["choices"][0]["message"]["content"]
		var emotion_result = extract_emotion(assistant_msg)
		var emo = emotion_result[0]
		var txt = emotion_result[1]
		
		conversation.append({"role": "assistant", "content": msg})
		emit_signal("response_received", emo, txt)
	else:
		push_error("HTTP 错误：%s, code=%d" % [result, code])

func _extract_emotion(text: String) -> Array:
	var regex = RegEx.new()
	regex.compile("\\[emotion=(\\w+)\\]\\n?")
	var m = regex.search(text)
	if m:
		return [m.get_string(1), text.replace(m.get_string(0), "")]
	return ["", text]
